#include <brpc/channel.h>
#include "main.pb.h"
#include <thread>

// 异步回调函数
void cb_func(brpc::Controller *controller, ns_brpc::EchoResponse *response)
{
    if (controller->Failed() == true)
    {
        std::cout << "rpc调用失败\n";
        return;
    }
    std::cout << "[ECHO]:" << response->message() << std::endl;
    delete controller;
    delete response;
}

int main()
{
    // 1、定义信道并初始化
    brpc::ChannelOptions options;                       // 信道参数
    options.connect_timeout_ms = -1;                    // 连接等待超时时间
    options.timeout_ms = -1;                            // rpc请求等待超时时间
    options.max_retry = 3;                              // 最大请求重试次数
    options.protocol = "baidu_std";                     // 序列化协议
    brpc::Channel channel;                              // 定义信道
    int ret = channel.Init("127.0.0.1:8080", &options); // 初始化
    if (ret == -1)
    {
        std::cout << "信道初始化失败\n";
        return -1;
    }

    // 2、定义ns_brpc::EchoServer_Stub对象，进行rpc调用
    // EchoServer_Stub是继承EchoServer类生成的，因为要用到里面的服务方法给客户端使用
    ns_brpc::EchoServer_Stub stub(&channel);

    brpc::Controller *controller = new brpc::Controller();
    ns_brpc::EchoResponse *response = new ns_brpc::EchoResponse();
    ns_brpc::EchoRequest request;
    request.set_message("这是一个测试信息\n");

    // 同步调用，不需要Closure
    stub.echo(controller, &request, response, nullptr);
    if (controller->Failed() == true)
    {
        std::cout << "rpc调用失败\n";
        return -1;
    }
    std::cout << "[ECHO]:" << response->message() << std::endl;
    delete controller;
    delete response;

    // // 异步调用
    // // 全局函数生成Closure对象, NewCallback有很多重载，支持很多类型的函数指针作为回调,controller,response是回调的参数
    // google::protobuf::Closure *done = google::protobuf::NewCallback(cb_func, controller, response);
    // stub.echo(controller, &request, response, done);
    // std::this_thread::sleep_for(std::chrono::seconds(20)); //异步调用需要阻塞主线程

    return 0;
}